<template name="specificationAre">
	<view class="specificationAre borderR">
		<view class="calc attr-content">
			<view class="display flow a-t">
				<view class="display flow title">
					<image :src="headImgUrl"></image>
					<view class="display column right">
						<block v-if="findSku">
							<text class="price">¥{{priceNum}}</text>
							<view class="selected">
								已选： <text class="selected-text" >{{selectedTxt}}</text>
							</view>
						</block>
						<!-- <text class="stock">库存{{ inventoryNum }}件</text> -->
						<block v-else>无货</block>
					</view>
					<uni-icons :type="'closeempty'" :color="blackColor" size="20" @click="skuCancle"/>
				</view>
			</view>
			<scroll-view scroll-y="true" style="max-height: 400rpx;">
				<dl v-for="(item, key) in skuGroup" :key="key" class="display column attr-list" >
					<dt> {{key}}</dt> 
					<dd class="display item-list">
						<text
							class="tit fontHide"
							v-for="(value,index) in item"
							:key="index"
							@click="toChooseItem(key,value)"
							:class="[array_contain(selectedProp,value)?'selected':'',props_contain(allProperties,selectedPropObj,key,value,propKeys)==0?'dashed':''] "
							> {{ value }} 
						</text> 
					</dd>
				</dl>
			</scroll-view>
			<view class="selectCount display flow borderB">
				<text>数量</text>
				<uni-number-box :min="1" :max="skuNum" :value="1" @change="numChange"/>
			</view>
		</view>
		<button class="completeBtn themeBgColor" @click="complete()" :disabled="!findSku">确认</button>
	</view>
</template>

<script>
	export default {
		name: 'specificationAre',
		props:{
			// attrList:{
			// 	type: Array,
			// 	default: Array
			// },
			headImg:{
				type: String,
				default: ''
			},
			price:{
				type: [String,Number],
				default: 0
			},
			goodsNum:{
				type: Number,
				default: 0
			},
		},
		data() {
			return {
				skuNum: 1,
				// price: 0,
				skuGroup: {},
				findSku: true,
				defaultSku: undefined,
				selectedProp: [],
				selectedPropObj: {},
				propKeys: [],
				allProperties: [],
				numberValue: this.goodsNum,
				attrList: [],
				blackColor: this.global.blackColor
			}
		},
		computed: {
			headImgUrl(){
				let pic = ''
				if(this.defaultSku){
					pic = this.defaultSku.img?this.defaultSku.img:this.headImg
				}else{
					pic = this.headImg
				}
				return pic
			},
			priceNum(){
				var that = this
				let price = that.price
				if(that.defaultSku){
					price = that.defaultSku.price
				}
				return price
			},
			inventoryNum(){
				var that = this
				if(that.defaultSku){
					that.skuNum = Number(that.defaultSku.num)
				}
				return that.skuNum
			},
			selectedTxt(){
				let text = ''
				// let text = this.selectedProp.length>0?this.selectedProp+'，':this.selectedProp,
				if(this.selectedProp.length == 1){
					text = this.selectedProp[0]
				}else if(this.selectedProp.length>0){
					for(let i in this.selectedProp){
						text += this.selectedProp[i]+'，'
					}
				}
				return text
			}
		},
		methods: {
			getData(){
				if(this.attrList.length!=0){
					for(let i in this.attrList){
						let properties = ''
						for(let j in this.attrList[i].attr_list){
							properties += this.attrList[i].attr_list[j].attr_group_name + ':' + this.attrList[i].attr_list[j].attr_name + ';'
						}
						this.attrList[i].properties = properties.substring(0,properties.length-1)
					}
					this.groupSkuProp()
				}
			},
			groupSkuProp: function() {
			    var skuList = this.attrList;
				console.log(skuList);
			    var skuGroup = {};//所有的规格名(包含规格名下的规格值集合）对象，如 {"颜色"：["金色","银色"],"内存"：["64G","256G"]}
			    var allProperties = [];//所有SKU的属性值集合，如 ["颜色:金色;内存:64GB","颜色:银色;内存:64GB"]
			    var propKeys = [];//所有的规格名集合，如 ["颜色","内存"]
			    for (var i = 0; i < skuList.length; i++) {
			
			      //找到和商品价格一样的那个SKU，作为默认选中的SKU
			      var defaultSku = this.defaultSku;
			      var isDefault = false;
			      if (!defaultSku && skuList[i].price == this.price) { 
			        defaultSku = skuList[i];
			        isDefault = true;
			        this.defaultSku = defaultSku
			      }
			      var properties = skuList[i].properties; //如：版本:公开版;颜色:金色;内存:64GB
			      allProperties.push(properties);
			      var propList = properties.split(";"); // 如：["版本:公开版","颜色:金色","内存:64GB"]
			
			      var selectedPropObj = this.selectedPropObj;
			      for (var j = 0; j < propList.length; j++) {
				
			        var propval = propList[j].split(":"); //如 ["版本","公开版"]
			        var props = skuGroup[propval[0]]; //先取出 规格名 对应的规格值数组
			
			        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
			        if (isDefault) {
			          propKeys.push(propval[0]);
			          selectedPropObj[propval[0]] = propval[1];
			        }
			
			        if (props == undefined) {
			          props = []; //假设还没有版本，新建个新的空数组
			          props.push(propval[1]); //把 "公开版" 放进空数组
			        } else {
			          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
			            props.push(propval[1]); //把 "公开版" 放进数组
			          }
			        }
			        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
			      }
			      this.selectedPropObj = selectedPropObj
			      this.propKeys = propKeys
			    }
			    this.parseSelectedObjToVals();
				this.skuGroup = skuGroup,
				this.allProperties = allProperties
				if (this.attrList.length == 1) {
					this.complete2()
				}
			},
			
			parseSelectedObjToVals: function() {
			    var selectedPropObj = this.selectedPropObj;
			    var selectedProperties = "";
			    var selectedProp = [];
			    for(var key in selectedPropObj) {
					selectedProp.push(selectedPropObj[key]);
					selectedProperties += key + ":" + selectedPropObj[key] + ";";
			    }
			    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
				this.selectedProp = selectedProp
				// console.log(this.selectedProp);
			    var findSku = false;
				console.log(selectedProperties);
			    for (var i = 0; i < this.attrList.length; i++) {
					// console.log(this.attrList[i].properties);
			      if (this.attrList[i].properties == selectedProperties) {
					  if(this.attrList[i].num != 0){
						  findSku = true;
					  }
			        this.defaultSku = this.attrList[i]
			        break;
			      }
			    }
			    this.findSku = findSku
			},
			 
			//点击选择规格
			toChooseItem: function(key,value) {
			    var selectedPropObj = this.selectedPropObj;
			    selectedPropObj[key] = value;
			    this.selectedPropObj = selectedPropObj
			    this.parseSelectedObjToVals();
			},
			
			//判断数组是否包含某对象
			array_contain: function(array, obj) {
				for (var i = 0; i < array.length; i++) {
					if (array[i] == obj){
						//如果要求数据类型也一致，这里可使用恒等号===
						return true;
					}
				}
				return false;
			},
			
			/**
			  * 当前规格值是否可以选择  
			  * 
			  * 参数说明：
			  * @param allProperties  ['颜色:金色;内存:64GB','颜色:金色;内存:256GB']
			  * @param selectedPropObj {'颜色':'金色','内存':'64GB'}
			  * @param propKeys ['颜色','内存']
			  * @param key 颜色
			  * @param item 金色
			  * 
			  * @return 0 可选但跟其他值不匹配  1 可选 
			  */
			props_contain(allProperties, selectedPropObj, key, item, propKeys) {
				var properties = "";
				selectedPropObj[key] = item;
				for (var j = 0; j < propKeys.length; j++) {
					properties += propKeys[j] + ":" + selectedPropObj[propKeys[j]] + ";";
				}
				properties = properties.substring(0, properties.length - 1);
				for (var i = 0; i < allProperties.length; i++) {
					if (properties == allProperties[i]) {
						return 1;
					}
				}
				return 0;
			},
			//数量选择
			numChange(value){
				// console.log(value);
				this.numberValue = value
			},
			complete(){
				// console.log(this.defaultSku);
				if(this.defaultSku.num != 0){
					this.$emit('getSku',this.defaultSku,this.numberValue)
				}
			},
			complete2(){
				// console.log(this.defaultSku);
				this.$emit('getSkuList',this.defaultSku)
			},
			skuCancle(){
				this.$emit('skuCancle')
			}
		},
		
	}
</script>

<style lang="scss">
	@import '@/common/css/specification.scss';
	/* 规格弹窗 */
	.specificationAre{
		@include width;
		@include backG;
	}
</style>
